package colorx

import (
	"image"
	"image/color"
)

// ChangeImgColor 修改图片中的颜色值为其他颜色
func ChangeImgColor(img image.Image, srcC, destC color.Color) *image.RGBA {
	unitImageWidth := img.Bounds().Max.X
	unitImageHeight := img.Bounds().Max.Y
	resultImage := image.NewRGBA(image.Rect(0, 0, unitImageWidth, unitImageHeight))
	dr, dg, db, _ := destC.RGBA()
	for x := 0; x < unitImageWidth; x++ {
		for y := 0; y < unitImageHeight; y++ {
			or, og, ob, oa := img.At(x, y).RGBA()
			var r, g, b, a uint8
			if srcC == nil {
				r, g, b, a = uint8(dr), uint8(dg), uint8(db), uint8(oa)
			} else {
				sr, sg, sb, sa := srcC.RGBA()
				// 比较一下颜色是否相同
				if or == sr && og == sg && ob == sb && oa == sa {
					r, g, b, a = uint8(dr), uint8(dg), uint8(db), uint8(oa)
				} else {
					r, g, b, a = uint8(or), uint8(og), uint8(ob), uint8(oa)
				}
			}
			resultImage.Set(x, y, color.NRGBA{R: r, G: g, B: b, A: a})
		}
	}
	return resultImage
}

func ColorToUint8(c color.Color) (r, g, b, a uint8) {
	r_, g_, b_, a_ := c.RGBA()
	r, g, b, a = uint8(r_), uint8(g_), uint8(b_), uint8(a_)
	return
}
